import asyncio, time
# 用协程实现一个计算平均数的函数
def coro_avg():
    total = 0
    length = 0
    while True:
        try:
            value = yield total/length
        except ZeroDivisionError:
            value = yield 0
        total += value
        length += 1

my_avg = coro_avg()
print(next(my_avg))
print(my_avg.send(5))
print(my_avg.send(4))
print(my_avg.send(3))
print(my_avg.send(2))
print(my_avg.send(1))


# 编写一个asyncio异步程序
class Response:
    staus_code = 200

async def sim_request(index):
    print(f"模拟发送请求 index:{index}")
    response = Response()
    await asyncio.sleep(1)
    print(f"request index:{index}, response staus_code:{response.staus_code}")
    return response.staus_code

loop = asyncio.get_event_loop()
task_array = []
for i in range(100):
    task_array.append(sim_request(i))

# loop.run_until_complete((asyncio.wait(task_array)))
result = loop.run_until_complete(asyncio.gather(*task_array))
print(result)
loop.close()
